import {ApiResponse} from '@/services/http';
import {useEffect, useReducer, useState} from 'react';
const initialState = {
  pageNum: 1,
  pageSize: 10,
};
const reducer = (state: typeof initialState, action: any) => {
  switch (action.type) {
    case 'setPageNum':
      return {...state, pageNum: action.payload};
    default:
      return state;
  }
};
const usePage = <R>(
  api: (params: any) => Promise<ApiResponse<{records: R[]; total: number}>>,
  params?: object,
) => {
  const [loading, setLoading] = useState(false);
  const [pageInfo, dispatch] = useReducer(reducer, initialState);
  const [total, setTotal] = useState<number | undefined>(0);
  const [hasMore, setHasMore] = useState(true);
  const [list, setList] = useState<R[]>([]);
  const [restData, setRestData] = useState<R | undefined>();
  useEffect(() => {
    if (pageInfo.pageNum === 1) {
      setList([]);
    }
    setLoading(true);
    api({
      ...pageInfo,
      ...params,
    })
      .then(res => {
        let {records, total, ...rest} = res.data;
        total = Number(total);
        total = isNaN(total) ? 0 : total;
        setRestData(rest as any);
        setList(pre => {
          if (pageInfo.pageNum === 1) {
            setTotal(total);
          }
          const result = [...pre, ...(records ?? [])];
          if (result.length === total) {
            setHasMore(false);
          }
          return result;
        });
      })
      .finally(() => {
        setLoading(false);
      });
  }, [pageInfo]);
  return {
    loading,
    list,
    pageInfo,
    dispatch,
    total,
    setTotal,
    hasMore,
    setHasMore,
    restData
  } as const;
};
export default usePage;
